﻿using Newtonsoft.Json.Linq;
using PetaPoco.NetCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BaseSimpleDao
{
    /// <summary>
    /// 基础帮助函数
    /// </summary>
    public static class BaseHelper
    {
        /// <summary>
        /// 根据数据类型获取表名
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetTableName(Type type)
        {
            TableNameAttribute attribute = (TableNameAttribute)type.GetCustomAttributes(typeof(TableNameAttribute), false).FirstOrDefault();

            if (attribute != null)
                return string.Format("{0}", attribute.Value);

            return string.Format("{0}", type.Name);
        }

        /// <summary>
        /// 让Sql拼接筛选器
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="filters"></param>
        public static void SqlLinkFilter(Sql sql, IEnumerable<BaseFilter> filters)
        {
            if (filters == null || filters.Count() == 0)
                return;

            foreach (var item in filters)
            {
                sql.Where(string.Format("[{0}] {1} {2}", item.Key, GetSqlOperation(item.Operation), GetSqlData(item.Value)));
            }
        }

        /// <summary>
        /// 让Sql拼接顺序
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="orders"></param>
        public static void SqlLinkOrder(Sql sql, IEnumerable<BaseOrder> orders)
        {
            if (orders == null || orders.Count() == 0)
                return;

            sql.OrderBy(orders.Select(n => string.Format("{0} {1}", n.Key, n.Order)).ToArray());
        }

        /// <summary>
        /// 将内容对象转换为Sql可以识别的对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetSqlData(object obj)
        {
            if (obj == null)
                return "NULL";

            var obj_type = obj.GetType();

            if (obj_type == typeof(string))
                return string.Format("\'{0}\'", obj);

            // 如果是列表类型则应该按照列表的语法来处理
            if (obj_type.IsArray || obj is System.Collections.IEnumerable)
            {
                List<object> list = new List<object>();

                foreach (var item in (System.Collections.IEnumerable)obj)
                {
                    list.Add(item);
                }

                return string.Format("({0})", string.Join(",", list));
            }

            if (obj_type == typeof(JArray))
            {
                var array = obj as JArray;

                List<object> items = new List<object>();

                foreach (var item in array)
                {
                    items.Add(item.ToString());
                }

                return string.Format("({0})", string.Join(",", items));
            }

            if (obj_type.IsEnum)
                return ((int)obj).ToString();

            return obj.ToString();
        }

        /// <summary>
        /// 根据类型获取全部的列名
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetColumnNames(Type type)
        {
            var p_list = type.GetProperties();
            List<string> c_list = new List<string>();

            string head = GetTableName(type);

            foreach (var item in p_list)
            {
                //var c_info = ColumnInfo.FromProperty(item);
                //c_list.Add(string.Format("{0}.{1}", head, c_info.ColumnName));

                //var c_info = ColumnAttribute.GetCustomAttribute(type, item.PropertyType);

                var c_info = (ColumnAttribute)type.GetCustomAttributes(typeof(ColumnAttribute), false)?.FirstOrDefault();
                c_list.Add(string.Format("{0}.{1}", head, c_info.Name));
            }

            return string.Join(",", c_list);
        }

        /// <summary>
        /// Sql操作符转换
        /// </summary>
        private static Dictionary<string, string> SqlOperationMapping = new Dictionary<string, string>()
        {
            //{ "=", "<>"},
        };

        /// <summary>
        /// 获取Sql的操作符
        /// </summary>
        /// <param name="operation"></param>
        /// <returns></returns>
        public static string GetSqlOperation(string operation)
        {
            if (SqlOperationMapping.ContainsKey(operation))
                return SqlOperationMapping[operation];

            return operation;
        }

        /// <summary>
        /// 获取当前的时间（秒）
        /// </summary>
        /// <returns></returns>
        public static long GetTimeNow()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }
    }
}
